package com.mewp.permissions.common.utils;

import com.mewp.permissions.model.po.SysMenu;
import com.mewp.permissions.model.vo.MetaVo;
import com.mewp.permissions.model.vo.RouterVO;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.LinkedList;
import java.util.List;

/**
 * 根据菜单数据构建路由的工具类
 *
 * @author mewp
 * @version 1.0
 * @date 2023/7/30 20:30
 */
public class RouterHelper {
    /**
     * 根据菜单构建路由
     *
     * @param menus 菜单列表
     * @return 路由列表
     */
    public static List<RouterVO> buildRouters(List<SysMenu> menus) {
        List<RouterVO> routers = new LinkedList<>();
        for (SysMenu menu : menus) {
            RouterVO routerVO = new RouterVO();
            routerVO.setHidden(false);
            routerVO.setAlwaysShow(false);
            routerVO.setPath(getRouterPath(menu));
            routerVO.setComponent(menu.getComponent());
            routerVO.setMeta(new MetaVo(menu.getName(), menu.getIcon()));
            List<SysMenu> children = menu.getChildren();
            //如果当前是菜单，需要将按钮对应的路由加载出来
            if (menu.getType() == 1) {
                List<SysMenu> hiddenMenuList = children.stream().filter(item ->
                        StringUtils.hasText(item.getComponent())).toList();
                for (SysMenu hiddenMenu : hiddenMenuList) {
                    RouterVO hiddenRouter = new RouterVO();
                    hiddenRouter.setHidden(true);
                    hiddenRouter.setAlwaysShow(false);
                    hiddenRouter.setPath(getRouterPath(hiddenMenu));
                    hiddenRouter.setComponent(hiddenMenu.getComponent());
                    hiddenRouter.setMeta(new MetaVo(hiddenMenu.getName(), hiddenMenu.getIcon()));
                    routers.add(hiddenRouter);
                }
            } else {
                if (!CollectionUtils.isEmpty(children)) {
                    routerVO.setAlwaysShow(true);
                    routerVO.setChildren(buildRouters(children));
                }
            }
            routers.add(routerVO);
        }
        return routers;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    private static String getRouterPath(SysMenu menu) {
        String routerPath = "/" + menu.getPath();
        if (menu.getParentId() != 0) {
            routerPath = menu.getPath();
        }
        return routerPath;
    }
}
